<script setup >
import { reactive, ref, onMounted } from 'vue';
import { getCode, login } from '@/api/Auth.js'
import { useRouter } from 'vue-router'
import { authstore } from '@/pinia/auth.js'
// 创建登录store
const authStore = authstore()
// 创建一个路由
const router = useRouter()
// 挂在就获取验证码
onMounted(() => {
  getValidCode()
  // token登录
  loginByToken()
})
// 获取验证码
const getValidCode = async () => {
  let res = await getCode()
  codeUrl.value = res.data.image
}
// 数据
const loginForm = reactive({
  username: '',
  password: '',
  verifyCode: ''
})
const codeUrl = ref('')
// 表单验证
const LoginRules = reactive({
  username: [
    { required: true, message: '请输入有效用户名', trigger: 'blur' },
    { min: 3, max: 15, message: '长度3-15', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入有效密码', trigger: 'blur' },
    { min: 3, max: 15, message: '长度3-15', trigger: 'blur' },
  ],
  verifyCode: [
    {
      required: true,
      whitespace: true,
      message: "不能为空格"
    }
  ]
})
// 登录动作
const handleToLogin = async () => {
  let res = await authStore.userlogin(loginForm)
  if (res == 'ok')
    router.push('/index')
}
// token登录
const loginByToken = () => {
  let token = localStorage.getItem('token')
  if (token) {
    authStore.userloginByToken(token)
  } else {

  }
}
</script>

<template>
  <div class="login-container">

    <div class="login-form">
      <!-- 标题 -->
      <header class="header">
        <img src="@/assets/gaia.png" alt="">
      </header>
      <el-form :model="loginForm" :rules="LoginRules" label-width="70px" label-position="right"
        style="padding: 0 80px;">
        <el-form-item prop="username" label="用户名">

          <el-input v-model="loginForm.username" placeholder="请输入用户名" value="admin" />
        </el-form-item>
        <el-form-item prop="password" label="密码">

          <el-input v-model="loginForm.password" type='password' placeholder="请输入密码" value="123456" />
        </el-form-item>
        <el-form-item prop="verifyCode" label="验证码">
          <el-input v-model="loginForm.verifyCode" />
          <div style="margin-top:10px  ;" @click="getValidCode">
            <img :src="codeUrl" alt="验证码">
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="info" plain @click="handleToLogin"> 登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>

</template>

<style lang="scss">
.login-container {
  width: 60%;
  height: 500%;
  padding: 20px 0;
  background-color: #ccc;
  margin: 10% auto;
  border-radius: 10px;

  .login-form {
    .header {
      margin: 35px 0;
      // display: flex;
      text-align: center;

      img {
        // justify-content: center;
        width: 100px;
        border-radius: 50%;

      }
    }

    width: 80%;
    margin: 10px auto;
  }
}
</style>